from flask import Blueprint, jsonify, request, json
import L_TMgmt.L_TOperation.trainOprt as trainOprt
import datetime

train = Blueprint('train', __name__)


@train.route('/init', methods=['GET'])
def init():
    if trainOprt.getAllTrain() == 0:
        return trainOprt.getAllTrain()
    else:
        trainlist = []
        for line in trainOprt.getAllTrain():
            trainlist.append({"train_id": line[0], "train_type": line[1],
                              "line_id": line[2], "line_name": line[3]})
        print(trainlist)
    return jsonify(trainlist)


@train.route('/item_line', methods=['GET'])
def item_department():
    print("get all line")

    if trainOprt.getAllLine() == 0:
        return trainOprt.getAllLine()
    else:
        linelist = []
        for line in trainOprt.getAllLine():
            linelist.append({"line_id": line[0], "line_name": line[1]})
        print(linelist)
        return jsonify(linelist)


@train.route('/newtrain', methods=['POST'])
def newtrain():
    print("new a train")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))

    if trainOprt.newtrain(json_data.get('line_id'), json_data.get('train_type')):
        return jsonify(1)
    else:
        return jsonify(2)


@train.route('/delete', methods=['POST'])
def trainDelete():
    data = request.get_data()
    print(data)
    word = data.decode("utf-8")
    print(word)
    if trainOprt.deleteTrain(word):
        return jsonify(1)
    else:
        return jsonify(2)


@train.route('/select', methods=['POST'])
def trainVagueSelect():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    word = json_data.get('word')
    trainlist = []
    if trainOprt.searchTrain(word) == 0:
        return jsonify(0)
    else:
        for line in trainOprt.searchTrain(word):
            trainlist.append({"train_id": line[0], "train_type": line[1],
                              "line_id": line[2], "line_name": line[3]})
        print(trainlist)
        return jsonify(trainlist)
